package jwlee.testitext;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.util.List;

import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.Anchor;
import com.lowagie.text.Annotation;
import com.lowagie.text.Cell;
import com.lowagie.text.Chapter;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.ListItem;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Section;
import com.lowagie.text.Table;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.rtf.RtfWriter2;

public class ITextTest {
	private static String path = System.getProperty("user.dir")
			+ "\\src\\jwlee\\testitext\\";
	
	private static void html2pdf() throws IOException, DocumentException {
		OutputStream out = new FileOutputStream(
				"src\\jwlee\\testitext\\html2pdf.pdf");

		Document document = new Document(PageSize.A4);
		PdfWriter.getInstance(document, out);
		document.open();

		//pdf转不出图片，word可以
//		String s = "上传的图片<img width=\"800\" height=\"600\" alt=\"\" src=\"D:\\Java\\projects\\mzjTestProject\\src\\jwlee\\testitext\\1.jpg\" />";
//		Reader reader = new StringReader(s);
		
		Reader reader = new FileReader("src\\jwlee\\testitext\\3.htm");
		StyleSheet ss = new StyleSheet();
		ss.loadTagStyle("body", "leading", "16,0"); 
		List htmlList = HTMLWorker.parseToList(reader, ss);
		BaseFont bfChinese = BaseFont.createFont("STSongStd-Light",
				"UniGB-UCS2-H", false);
		Font fontChinese = new Font(bfChinese, 12, Font.NORMAL, Color.BLACK);
		Paragraph content = new Paragraph("html转pdf：", fontChinese);
		for (int i = 0; i < htmlList.size(); i++) {
			System.out.println(i + ":--------------------------------------");
			Element e = (Element) htmlList.get(i);
			System.out.println(e);
			content.add(e);
		}
		document.add(content);
		document.close();
	}

	private static void html2word() throws IOException, DocumentException {
		OutputStream out = new FileOutputStream("src\\jwlee\\testitext\\html2word.doc");
		
		Document document = new Document(PageSize.A4);
		RtfWriter2.getInstance(document, out);
		document.open();
		
		String s = "上传的图片<img width=\"800\" height=\"600\" alt=\"\" src=\"D:\\Java\\projects\\mzjTestProject\\src\\jwlee\\testitext\\1.jpg\" />";
		Reader reader = new StringReader(s);
//		Reader reader = new FileReader("src\\jwlee\\testitext\\3.htm");
		StyleSheet ss = new StyleSheet();
		List htmlList = HTMLWorker.parseToList(reader, ss);
		BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",
					false);
		Font fontChinese = new Font(bfChinese, 12, Font.NORMAL, Color.BLACK);
		Paragraph content = new Paragraph("html转word：", fontChinese);
		for (int i = 0; i < htmlList.size(); i++) {
			System.out.println(i+":-----------------------------------------");
			Element e = (Element) htmlList.get(i);
			System.out.println(e);
			content.add(e);
		}
		document.add(content);
		document.close();
	}
	
	private static void html2word2() throws IOException, DocumentException {
		StringBuffer buf = new StringBuffer();
		buf.append("<html>\n");
		// put in some style
		buf.append("<head><style language='text/css'>");
		buf.append("<!-- h3 { border: 1px solid #aaaaff; background: #ccccff;");
		buf.append("padding: 1em; text-transform: capitalize; font-family: sansserif; font-weight: normal;}");
		buf.append("p { margin: 1em 1em 4em 3em; } p:first-letter { color: red; font-size: 150%; }");
		buf.append("h2 { background: #5555ff; color: white; border: 10px solid black; padding: 3em; font-size: 200%; }");
		buf.append("--></style></head>\n");
		// generate the body
		buf.append("<body>");
		buf.append("<p><img src='"+path+"1.jpg'/></p>\n");
		for (int i = 9; i > 0; i--) {
			buf.append("<h3>" + i + " bottles of beer on the wall," + i
					+ " bottles of beer!</h3>");
			buf.append("<p>Take one down and pass it around," + (i - 1)
					+ " bottles of beer on the wall</p>\n");
		}
		buf.append("<h2>No more bottles of beer on the wall, no more bottles of beer.");
		buf.append("Go to the store and buy some more, 99 bottles of beer on the wall.</h2>");
		buf.append("</body>\n");
		buf.append("</html>");
		
		File f = new File("src\\jwlee\\testitext\\html2word.doc");
		OutputStream out = new FileOutputStream(f);
		Document document = new Document(PageSize.A4);
		RtfWriter2.getInstance(document, out);
		document.open();
		Paragraph content = new Paragraph(buf.toString());
		document.add(content);
		document.close();
		System.out.println(f.getAbsolutePath());
	}

	private static void generatePdf(String filename) {
		Document document = new Document(PageSize.A4, 36, 36, 20, 20);
		try {
			PdfWriter writer = PdfWriter.getInstance(document,
					new FileOutputStream(filename + ".pdf"));
			document.open();
			PdfContentByte cb = writer.getDirectContent();
			BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
					BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
			cb.beginText();
			cb.setFontAndSize(bf, 16);
			cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
					"Text generate by PdfContentByte", 250, 700, 0);
			cb.endText();

			ColumnText ct = new ColumnText(cb);
			Phrase phrase = new Phrase(
					"PdfContentBytePdfContentBytePdfContentByte");
			ct.setSimpleColumn(phrase, 60, 300, 200, 500, 15,
					Element.ALIGN_CENTER);
			ct.go();

			addContents(document);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		document.close();
	}

	private static void generateRtf(String filename) {
		Document document = new Document(PageSize.A4, 36, 36, 20, 20);
		try {
			RtfWriter2.getInstance(document, new FileOutputStream(filename
					+ ".doc"));
			document.open();
			addContents(document);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		document.close();
	}

	private static void addContents(Document document)
			throws DocumentException, MalformedURLException, IOException {
		Table table = new Table(3);
		int width[] = { 25, 25, 50 };
		table.setWidths(width);
		table.setWidth(80);
		table.setAutoFillEmptyCells(true);
		table.setPadding(1);
		table.setSpacing(1);
		table.setBorder(1);
		Cell headCell = new Cell("header");
		headCell.setHeader(true);
		headCell.setColspan(3);
		headCell.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(headCell);
		table.endHeaders();// 表头结束

		Cell cell0 = new Cell(new Phrase("#0"));
		cell0.setVerticalAlignment(Element.ALIGN_MIDDLE);
		cell0.setRowspan(3);
		table.addCell(cell0);
		table.addCell(new Cell("#1"));
		table.addCell(new Cell("#2"));
		table.addCell(new Cell("#3"));
		table.addCell(new Cell("#4"));
		table.addCell(new Cell("#5"));
		table.addCell(new Cell("#6"));
		document.add(table);

		BaseFont bfChinese = null;
		try {
			bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",
					false);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		Font fontChinese = new Font(bfChinese, 12, Font.NORMAL, Color.BLACK);
		Paragraph contents = new Paragraph("你好！测试iText2！", fontChinese);
		document.add(contents);

		Paragraph p2 = new Paragraph(new Phrase("Paragraph 2nd: Phrase!"));
		document.add(p2);

		Paragraph p3 = new Paragraph(new Chunk("Paragraph 3rd: Chunk!"));
		p3.add("\nAdd strings...\n");
		p3.add(new Phrase("Add phrases...\n", new Font()));
		p3.add(new Chunk("Add chunks...\n"));

		Anchor anchor = new Anchor("anchor to dc\n\n");
		anchor.setName("digitalchina");
		anchor.setReference("www.digitalchina.com");
		p3.add(anchor);
		Anchor anchor2 = new Anchor("inner anchor");
		anchor2.setReference("#digitalchina");
		p3.add(anchor2);
		p3.add("\n\n");
		document.add(p3);

		com.lowagie.text.List list = new com.lowagie.text.List(true, 20);
		list.add(new ListItem("first"));
		list.add(new ListItem("second"));
		list.setNumbered(false);
		list.add(new ListItem("third"));
		document.add(list);

		Annotation a = new Annotation("annotation", "this is mzj's test!");
		document.add(a);

		HeaderFooter header = new HeaderFooter(new Phrase("测试iText"), false);
		header.setAlignment(Rectangle.ALIGN_CENTER);
		document.setHeader(header);
		HeaderFooter footer = new HeaderFooter(
				new Phrase("mzj: This is page "), true);
		footer.setBorder(Rectangle.ALIGN_CENTER);
		document.setFooter(footer);

		Paragraph title = new Paragraph("chapter");
		Chapter chapter = new Chapter(title, 1);
		chapter.setNumberStyle(Section.NUMBERSTYLE_DOTTED);
		Section section1 = chapter.addSection(new Paragraph("section1"), 2);
		Section section2 = chapter.addSection(new Paragraph("section2"), 2);
		section1.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
		section2.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT);
		document.add(chapter);

		Image jpg = Image.getInstance("src\\jwlee\\testitext\\1.jpg");
		jpg.scalePercent(50);
		document.add(jpg);
		Image gif = Image.getInstance("src\\jwlee\\testitext\\1.gif");
		document.add(gif);

		BaseFont bfLi = BaseFont.createFont("C:\\Windows\\Fonts\\STLITI.TTF",
				BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		Font font = new Font(bfLi, 32);
		String text = "这是隶书字体测试！";

		document.add(new Paragraph(text, font));

	}

	public static void main(String[] args) {
		String filename = "src\\jwlee\\testitext\\IText";
		//generatePdf(filename);
		//generateRtf(filename);

		try {
//			html2pdf();
//			html2word();
			html2word2();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
